//index.js
const app = getApp()
Page({
  data: {
    uid: '',
    longitude: 0,
    latitude: 0,
    markers: []
  },

  onLoad: async function() {
    try {
      const { result } = await wx.cloud.callFunction({name: 'getuserid'})
      // 获取openid
      const { openid: uid, permission } = result
      this.setData({
        uid: uid
      })
      // 获取权限显示审核导航
      if (permission) {
        if (typeof this.getTabBar === 'function' &&
          this.getTabBar()) {
          const list = this.getTabBar().data.list.slice()
          const adminList = this.getTabBar().data.adminList.slice()
          const newList = [...list, ...adminList]
          this.getTabBar().setData({
            list: newList
          })
        }
      }
    } catch (error) {
      console.log(error)
    }
  },
  
  onShow: function() {
    // 导航选中状态
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0
      })
    }
    this.getAddressDetail()
  },

  onReady: function () {
  },

  /**
     * 获取地理位置信息详情
     */
  getAddressDetail: function () {
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userLocation']) {
          wx.getLocation({
            type: 'wgs84',
            success: ({latitude = 0, longitude = 0}) => {
              this.setData({
                latitude,
                longitude
              })
              this.sendRequest()
            },
            fail: err => {
              console.log(err)
            }
          })
        } else {
          this.errMessage('无法获取位置信息')
        }
      },
      fail: err => {
        console.log(err)
      }
    })
  },


  /**
   * 发送请求获取地图接口的返回值
   */
  sendRequest: function () {
    let that = this
    wx.showLoading()
    // 调用请求
    // console.log(that.data.longitude, that.data.latitude, 'location')
    wx.cloud.callFunction({
      name: 'warnlist',
      data: {
        longitude: that.data.longitude,
        latitude: that.data.latitude
      },
      success: ({ result }) => {
        // console.log(result, 'result')
        const { data = [] } = result
        const markerArr = data.map(
          marker => {
            const icon = `/images/local/local-${marker._openid === that.data.uid ? 'red' : 'green'}.png`
            return {
              iconPath: icon,
              id: marker._id,
              latitude: marker.location[1],
              longitude: marker.location[0],
              width: 35,
              height: 35
            }
          }
        )
        const MAX_LIMIT = 50
        if (markerArr.length > MAX_LIMIT) {
          const batchTimes = Math.ceil(markerArr / MAX_LIMIT)
          for (let i = 0; i < batchTimes; i++) {
            const newArr = markerArr.slice(i * MAX_LIMIT, (i + 1) * MAX_LIMIT)
            setTimeout(() => {
              that.setData({
                markers: that.data.markers.concat(newArr)
              })
            }, 0)
            if (i === 1) {
              wx.hideLoading()
            }
          }
        } else {
          that.setData({
            markers: markerArr
          })
          wx.hideLoading()
        }
      },
      fail: err => {
        console.log(err)
      }
    })
  },
  // 更新当前坐标
  locationSet: function () {
    wx.showLoading()
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userLocation']) {
          wx.getLocation({
            type: 'wgs84',
            success: ({latitude = 0, longitude = 0}) => {
              this.setData({
                latitude,
                longitude
              })
              wx.hideLoading()
            },
            fail: err => {
              wx.hideLoading()
              console.log(err)
            }
          })
        } else {
          wx.hideLoading()
          this.errMessage('无法获取位置信息')
        }
      },
      fail: err => {
        wx.hideLoading()
        console.log(err)
      }
    })
  },
  // 点击marker跳转查看
  markertap: function (e) {
    wx.navigateTo({
      url: `/pages/showInfo/showInfo?markerID=${e.markerId}&state=view`,
      success: function(res) {
        // 通过eventChannel向被打开页面传送数据
        // console.log('成功')
      }
    })
  },
  // 跳转编辑页
  editInfo: function () {
    wx.navigateTo({
      url: `/pages/sendInfo/sendInfo`
    })
  },

  errMessage: function (title = '', duration = 2000) {
    wx.showToast({
      title,
      icon: 'none',
      duration
    })
  }
})
